/*
 * Copyright 2009 Jesse McLaughlin (nzjess@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.travelfusion.xmlclient.impl;

import static org.travelfusion.xmlclient.util.TfXSPIUtil.checkResponse;
import static org.travelfusion.xmlclient.util.TfXSPIUtil.ensureStreamSupportsMark;
import static org.travelfusion.xmlclient.util.TfXSPIUtil.findCommandTag;

import java.io.IOException;
import java.io.InputStream;

import org.travelfusion.xmlclient.TfXClient;
import org.travelfusion.xmlclient.cache.CacheEntry;
import org.travelfusion.xmlclient.cache.CacheProvider;
import org.travelfusion.xmlclient.exception.TfXClientException;
import org.travelfusion.xmlclient.handler.HandlerPipeline;
import org.travelfusion.xmlclient.handler.HandlerPipelineFactory;
import org.travelfusion.xmlclient.handler.RequestHandler;
import org.travelfusion.xmlclient.handler.RequestHandlerInterceptor;
import org.travelfusion.xmlclient.handler.ResponseHandler;
import org.travelfusion.xmlclient.handler.ResponseHandlerInterceptor;
import org.travelfusion.xmlclient.handler.stream.StreamResponseHandler;
import org.travelfusion.xmlclient.login.Login;
import org.travelfusion.xmlclient.login.LoginManager;
import org.travelfusion.xmlclient.transport.TfXTransport;
import org.travelfusion.xmlclient.xobject.XRequest;
import org.travelfusion.xmlclient.xobject.XResponse;

import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * Standard implementation of {@link TfXClient}. This class combines a {@link TfXTransport}, a
 * {@link HandlerPipelineFactory} instance, a {@link CacheProvider}, and a {@link LoginManager} to yield the standard
 * request/response processing pipeline such that all the semantics documented in those interfaces are provided. It also
 * provides built-in response stream checking so that unsuccessful responses from the TRAVELfusion XML service are
 * automatically parsed and thrown back to the caller via a {@link TfXClientException} (or an appropriate sub-class).
 * 
 * @see TfXClient
 * @see TfXTransport
 * @see HandlerPipelineFactory
 * @see CacheProvider
 * @see LoginManager
 * 
 * @author Jesse McLaughlin (nzjess@gmail.com)
 * @author Ana Henneberke (ana.henneberke@gmail.com)
 */
@Singleton
public class TfXClientImpl implements TfXClient {

  private HandlerPipelineFactory factory;

  private TfXTransport transport;

  private CacheProvider cacheProvider;

  private LoginManager loginManager;
  
  private String requestString;

  @Inject
  public void setFactory(HandlerPipelineFactory factory) {
    this.factory = factory;
  }

  @Inject
  public void setTransport(TfXTransport transport) {
    this.transport = transport;
  }

  @Inject(optional = true)
  public void setCacheProvider(CacheProvider cacheProvider) {
    this.cacheProvider = cacheProvider;
  }

  @Inject(optional = true)
  public void setLoginManager(LoginManager loginManager) {
    this.loginManager = loginManager;
  }

  /**
   * {@inheritDoc}
   */
  @Invoke
  public XResponse invoke(XRequest request) throws TfXClientException, IOException {
	requestString = "";
    try {
      // if there is a login manager, invoke it in order to identify the caller
      Login login = null;
      if (loginManager != null) {
        login = loginManager.getLogin(request);
      }

      // the response to be generated for the given request
      XResponse response = null;

      // if there is a cache provider then check cache
      CacheEntry cacheEntry = null;
      if (cacheProvider != null) {
        cacheEntry = cacheProvider.checkCache(login, request);
        if (cacheEntry != null) {
          response = cacheEntry.getResponse();
          if (response != null) {
            // return cached response
            return response;
          }
        }
      }

      // try/finally here ensures we always callback with a cache update, even on failure (cache friendly)      
      try {
        // create pipeline to handle request
        HandlerPipeline pipeline = factory.createHandlerPipeline(request);

        // execute request pipeline
        RequestHandler<XRequest> requestHandler = pipeline.getRequestHandler();
        RequestHandlerInterceptor requestHandlerInterceptor = pipeline.getRequestHandlerInterceptor();
        if (requestHandlerInterceptor != null) {
          requestHandlerInterceptor.beforeRequest(login, requestHandler, request);
        }
        requestString = requestHandler.handleRequest(login);
        if (requestHandlerInterceptor != null) {
          requestHandlerInterceptor.afterRequest(requestHandler, request);
        }

        // parse out request command tag so we can compare it to response later
        String requestCommandTag = findCommandTag(requestString);

        InputStream responseStream = null;
        try {
          // send request as string via transport (eg. to TRAVELfusion TripPlannerXML service), and receive response
          // stream
          responseStream = ensureStreamSupportsMark(transport.send(request, requestString));

          // check that the request resulted in a successful response. if not, the response xml will be parsed and an
          // exception will be thrown that contains error information parsed from the unsuccessful response
          // (this means that only successful responses are passed to the response processing stage of the pipeline).
          // assume initial 512 bytes is enough to determine if response is successful or not
          checkResponse(responseStream, requestCommandTag, 512);

          // success, execute response pipeline
          ResponseHandler<XRequest, XResponse> responseHandler = pipeline.getResponseHandler();

          // special case: stream response handler
          if (responseHandler instanceof StreamResponseHandler) {
            ((StreamResponseHandler<XRequest, XResponse>)responseHandler).setResponseStream(responseStream);;
          }

          ResponseHandlerInterceptor responseHandlerInterceptor = pipeline.getResponseHandlerInterceptor();
          if (responseHandlerInterceptor != null) {
            responseHandlerInterceptor.beforeResponse(responseHandler, responseStream);
          }
          response = responseHandler.handleResponse();
          if (responseHandlerInterceptor != null) {
            responseHandlerInterceptor.afterResponse(responseHandler, response);
          }
        }
        finally {
          // ensure response stream is closed
          if (responseStream != null) responseStream.close();
        }
      }
      finally {
        // update cache, if necessary
        if (cacheEntry != null) {
          response = cacheEntry.putResponse(response);
        }
      }

      // return the response to the caller
      return response;
    }
    catch (RuntimeException e) {
      throw new TfXClientException("Runtime Exception: " + e.getMessage() + " request: " + requestString, e);
    }
    catch (Exception e) {
      throw new TfXClientException(e.getMessage() + " request: " + requestString, e);
    }
  }

  @Override
  public XResponse invokeIgnoreCache(XRequest request) throws TfXClientException, IOException {
    // if there is a login manager, invoke it in order to identify the caller
    Login login = null;
    if (loginManager != null) {
      login = loginManager.getLogin(request);
    }
    cacheProvider.invalidateCache(login, request);
    return this.invoke(request);
  }

}
